奇怪的电梯

题目 奇怪的电梯

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 i 层楼(\(1 \le i \le N\))上有一个数字 K_i(\(0 \le K_i \le N\))。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如: 3, 3, 1, 2, 5 代表了 K_i(\(K_1=3\), \(K_2=3\),……),从 1 楼开始。在 1 楼,按“上”可以到 4 楼,按“下”是不起作用的,因为没有 -2 楼。那么,从 A 楼到 B 楼至少要按几次按钮呢?

输入格式

共二行。

第一行为三个用空格隔开的正整数,表示 N, A, B(\(1 \le N \le 200\), \(1 \le A, B \le N\))。

第二行为 N 个用空格隔开的非负整数,表示 \(K_i\)。

输出格式

一行,即最少按键次数,若无法到达,则输出 -1

样例 #1

样例输入 #1

5 1 5
3 3 1 2 5

样例输出 #1

3

提示

对于 $100 % $ 的数据,\(1 \le N \le 200\), \(1 \le A, B \le N\),\(0 \le K_i \le N\)。

本题共 16 个测试点,前 15 个每个测试点 6 分,最后一个测试点 10 分。

思路分析

image-05c5e058

我的想法是 从第一个楼层开始 有往上走和往下走两种情况(当然也可以不走 但是不走就永远到不了目标楼层) 只要能走(合法)就走到移动后的楼层 再对到达的这个楼层进行往上或往下的选择 直到到达目标楼层 这个过程要维护一个最小的次数 所以多传了一个cnt进来

可能太暴力了 把系统栈给爆了 显示mle

#include<bits/stdc++.h>

using namespace std;

const int N=210;

int went[N];

int n,A,B;

int res=0x3f3f3f;

void dfs(int cur,int cnt){

	if(cur==B){

		res=min(res,cnt);

		return;

	}

	if(cur-went[cur]>0)

		dfs(cur-went[cur],cnt+1);

	if(cur+went[cur]<=n)

		dfs(cur+went[cur],cnt+1);

}

int main()

{

	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);

	cin>>n>>A>>B;

	for(int i=1;i<=n;i++){

		cin>>went[i];

	}

	dfs(A,0);

	cout<<res;

	return 0;

 }
image-810bda9e

但想了一下也没找到剪枝的点

666666

以一种贪心的思路

image-6d9a96cd

若存在两种方案 都可以从第一层走到第五层 则一定是不走回头路的方案更优 也就是说 同一个楼层不应该被走两次

那么——就可以用全排列的思想(每个位置只出现一次)

使用st数组记录每个数是否用到过

#include<bits/stdc++.h>

using namespace std;

const int N=210;

int went[N];

int n,A,B;

int res=0x3f3f3f;

bool st[N];

void dfs(int cur,int cnt){

	if(cur<0 || cur>n)

		return;

	if(cur==B){

		res=min(res,cnt);

		return;

	}

	st[cur]=true;

	if(cur-went[cur]>0 && !st[cur-went[cur]]){

		st[cur-went[cur]]=true;

		dfs(cur-went[cur],cnt+1);

		st[cur-went[cur]]=false;

	}

	if(cur+went[cur]<=n && !st[cur+went[cur]]){

		st[cur+went[cur]]=true;

		dfs(cur+went[cur],cnt+1);

		st[cur+went[cur]]=false;

	}

}

int main()

{

	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);

	cin>>n>>A>>B;

	for(int i=1;i<=n;i++){

		cin>>went[i];

	}

	dfs(A,0);

	if(res==0x3f3f3f){

		cout<<"-1"<<endl;

		return 0;

	}

	cout<<res<<endl;

	return 0;

 }
image-7d615df6

虽然还是过不了 但是这个确实值得借鉴

代码实现


同类题型

视频讲解


⬅️ PERKET 🏠 00-刷题理模型 ➡️ 指数型(每个位置都可以选所有情况)